package com.leyou.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.config.UploadProperties;
import com.leyou.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
@EnableConfigurationProperties(UploadProperties.class)
public class UploadServiceImpl implements UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UploadProperties properties;

    // private static final List<String> CONTENT_TYPE = Arrays.asList("image/jpeg", "image/gif", "image/png");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Override
    public String upload(MultipartFile file) {
        String url = null;
        // 检验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if(!properties.getAllowTypes().contains(contentType)){
            LOGGER.info("文件类型不合法：{}", originalFilename);
            throw new LyException(ExceptionEnum.FILE_TYPE_ILLEGAL);
        }
        try{
            // 校验文件的内容
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("文件内容不合法：{}", originalFilename);
                throw new LyException(ExceptionEnum.FILE_CONTENT_ILLEGAL);
            }
            // 保存到服务器
            // file.transferTo(new File("E:\\life-imgs\\" + originalFilename));
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            // 生成url地址，返回
            url = properties.getBaseUrl() + storePath.getFullPath();
        }catch (IOException e){
            LOGGER.info("服务器内部错误：{}", originalFilename);
            e.printStackTrace();
        }
        return url;
    }
}
